
from django.db import transaction

from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response

from mail.serializer import *
from rest_framework import status
from utils.login_util import operation_log
from utils.mali_qq import EmailTool





# 邮件管理
class QQEmail(ModelViewSet):
    queryset = Mail.objects.filter(logic_del=0).all()
    serializer_class = MailSer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'

    def list(self, request, *args, **kwargs):
        user = request.session.get('user')
        uid = user['user_id']

        mails = Mail.objects.filter(consignee=uid, is_read=False, logic_del=0).all()
        # ser = MailSer(mails, many=True)
        mails_list = []
        for i in mails:
            user_mails = Email.objects.filter(user_id=i.user_id).first().email
            data = {
                "user_mails": user_mails,
                "is_read": i.is_read,
                "url": i.url,
                "consignee": i.consignee,
                "title": i.title,
                "content": i.content
            }
            mails_list.append(data)
        mail_copy = MailCopy.objects.filter(copy_id=uid, logic_del=0).all()

        for j in mail_copy:
            mails = Mail.objects.filter(id=j.mail_msg_id, is_read=False, logic_del=0).first()
            user_mails = Email.objects.filter(user_id=mails.user_id).first().email
            data = {
                "user_mails": user_mails,
                "is_read": mails.is_read,
                "url": mails.url,
                "consignee": mails.consignee,
                "title": mails.title,
                "content": mails.content
            }
            mails_list.append(data)
        return Response({"code": status.HTTP_200_OK, "msg": "获取收件箱成功", "data": mails_list})

    def create(self, request, *args, **kwargs):
        user = request.session.get('user')
        uid = user['user_id']
        # 查询登录的用户的邮箱信息
        email1 = Email.objects.filter(user_id=uid, logic_del=0).first()
        print(email1)
        recipients_url = request.data.get("recipients_url")
        title = request.data.get("title")
        copy = request.data.get("copy")
        content = request.data.get("content")
        # 根据邮箱地址获取邮箱信息
        email_name = Email.objects.filter(email=recipients_url, logic_del=0).first()

        email = email1.email  # 发送人的邮箱
        e_key = email1.secret_key  # 发送人邮箱的密钥
        recipients_list = []
        recipients_list.append(recipients_url)
        if len(copy) > 0:
            # copy = json.loads(copy)
            print("copy", copy, type(copy))
            for i in copy:
                email_add = Email.objects.filter(user_id=i, logic_del=0).first()
                recipients_list.append(email_add.email)
        for j in recipients_list:
            rest = EmailTool().sendmail(email, e_key, j, title, content)
            if not rest:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "发送失败"})
            # 开启事务
            with transaction.atomic():
                # 设置回滚点
                point = transaction.savepoint()
                try:
                    # 添加邮件信息
                    mail = Mail.objects.create(user_id=uid, url=recipients_url, consignee=email_name.user_id,
                                               title=title, content=content)
                    mail.save()
                    email_id = mail.id
                    if len(copy) > 0:
                        for x in copy:
                            # 添加邮寄查送人信息
                            mailcopy = MailCopy.objects.create(mail_msg_id=email_id, copy_id=x)
                            mailcopy.save()
                            operation_log(request, "抄送了一份邮件")
                            return Response({"code": status.HTTP_200_OK, "msg": "发送成功"})
                    operation_log(request, "发送了一份邮件")
                    return Response({"code": status.HTTP_200_OK, "msg": "发送成功"})
                except Exception as e:
                    print("发送邮件错误", e)
                    transaction.savepoint_rollback(point)
                    return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": f"发送邮件错误{e}"})






